package com.chilly.netty.action.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * Created by Chilly Cui on 2021/1/13.
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //读取数据
    //msg客户端发送的数据, 默认是object
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server ctx = [" + ctx + "]");
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("client msg=[" + byteBuf.toString(CharsetUtil.UTF_8) + "]");
        System.out.println("client addr=[" + ctx.channel().remoteAddress() + "]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello client~", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
